package com.jdy.haoduoaiteacher.receiver;

import android.content.Context;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;

import com.jdy.haoduoaiteacher.MyTeacherApp;
import com.jdy.haoduoaiteacher.activity.LoginActivity;
import com.jdy.haoduoaiteacher.activity.MainActivity;
import com.jdy.haoduoaiteacher.model.CarlaClassicVo;
import com.jdy.haoduoaiteacher.model.LeUser;
import com.jdy.haoduoaiteacher.util.HttpUtils;
import com.jdy.haoduoaiteacher.util.LeConfig;
import com.jdy.haoduoaiteacher.util.ResponseResult;
import com.jdy.haoduoaiteacher.util.Tools;
import com.tencent.android.tpush.XGPushBaseReceiver;
import com.tencent.android.tpush.XGPushClickedResult;
import com.tencent.android.tpush.XGPushRegisterResult;
import com.tencent.android.tpush.XGPushShowedResult;
import com.tencent.android.tpush.XGPushTextMessage;

import org.json.JSONException;
import org.json.JSONObject;

import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.HashMap;

//import com.jdy.haoduoaiteacher.activity.RecordActivity;
//import com.jdy.haoduoaiteacher.activity.SpeakForYouActivity;

/**
 *
 * @author hufei
 *
 */
public class XGMessageReceiver extends XGPushBaseReceiver {
  private final Intent intent = new Intent(
      "com.jdy.haoduoaiteacher.activity.NOTIFICATION_SHOW");
  public static final String LogTag = "TPushReceiver";

  private LeUser mLeUser;

  private void show(Context context, String text) {
    // Toast.makeText(context, text, Toast.LENGTH_SHORT).show();
  }

  // 通知展示
  @Override
  public void onNotifactionShowedResult(Context context,
      XGPushShowedResult notifiShowedRlt) {
    if (context == null || notifiShowedRlt == null) {
      return;
    }
    XGNotification notific = new XGNotification();
    notific.setMsg_id(notifiShowedRlt.getMsgId());
    notific.setTitle(notifiShowedRlt.getTitle());
    notific.setContent(notifiShowedRlt.getContent());
    // notificationActionType==1为Activity，2为url，3为intent
    notific.setNotificationActionType(notifiShowedRlt
        .getNotificationActionType());
    // Activity,url,intent都可以通过getActivity()获得
    notific.setActivity(notifiShowedRlt.getActivity());
    notific.setUpdate_time(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss")
        .format(Calendar.getInstance().getTime()));
    // NotificationService.getInstance(context).save(notific);
    context.sendBroadcast(intent);
    // show(context, "您有1条新消息, " + "通知被展示 ， " + notifiShowedRlt.toString());
  }

  @Override
  public void onUnregisterResult(Context context, int errorCode) {
    if (context == null) {
      return;
    }
    // String text = "";
    // if (errorCode == XGPushBaseReceiver.SUCCESS) {
    // text = "反注册成功";
    // } else {
    // text = "反注册失败" + errorCode;
    // }
    // Log.d(LogTag, text);
    // show(context, text);
  }

  @Override
  public void onSetTagResult(Context context, int errorCode, String tagName) {
    if (context == null) {
      return;
    }
    // String text = "";
    // if (errorCode == XGPushBaseReceiver.SUCCESS) {
    // text = "\"" + tagName + "\"设置成功";
    // } else {
    // text = "\"" + tagName + "\"设置失败,错误码：" + errorCode;
    // }
    // Log.d(LogTag, text);
    // show(context, text);
  }

  @Override
  public void onDeleteTagResult(Context context, int errorCode, String tagName) {
    if (context == null) {
      return;
    }
    // String text = "";
    // if (errorCode == XGPushBaseReceiver.SUCCESS) {
    // text = "\"" + tagName + "\"删除成功";
    // } else {
    // text = "\"" + tagName + "\"删除失败,错误码：" + errorCode;
    // }
    // Log.d(LogTag, text);
    // show(context, text);

  }

  // 通知点击回调 actionType=1为该消息被清除，actionType=0为该消息被点击
  @Override
  public void onNotifactionClickedResult(Context context,
      XGPushClickedResult message) {
    if (context == null || message == null) {
      return;
    }
    String text = "";
    if (message.getActionType() == XGPushClickedResult.NOTIFACTION_CLICKED_TYPE) {
      // 通知在通知栏被点击啦。。。。。
      // APP自己处理点击的相关动作
      // 这个动作可以在activity的onResume也能监听，请看第3点相关内容
      text = "通知被打开 :" + message;

      // 获取自定义key-value
      String customContent = message.getCustomContent();
      if (customContent != null && customContent.length() != 0) {
        try {
          JSONObject obj = new JSONObject(customContent);
          // key1为前台配置的key
          if (LeConfig.isLogin) {
            mLeUser = MyTeacherApp.getInstance().getUserTeacher();
            if (mLeUser == null) {
              mLeUser = Tools.restoreLeUser();
            }
            if (!obj.isNull("d")) {
              String value = obj.getString("d");
              int itemId = -1;
              if (Tools.isNotEmpty(value)) {
                if (value.contains("cartoon")) {
//                  if (obj.has("id") && obj.getInt("id") > 0) {
//                    itemId = obj.getInt("id");
//                    Intent intent = new Intent();
//                    intent.setClass(context, StoryDetailActivity.class);
//                    intent.putExtra("id", itemId);
//                    context.startActivity(intent);
//                  } else {
//                    toMainPage(context);
//                  }
                } else if (value.contains("radio")) {
//                  if (obj.has("id") && obj.getInt("id") > 0) {
//                    itemId = obj.getInt("id");
//                    Intent intent = new Intent();
//                    intent.setClass(context, RadioDetailActivity.class);
//                    intent.putExtra("id", itemId);
//                    context.startActivity(intent);
//                  } else {
//                    toMainPage(context);
//                  }
                } else if (value.contains("story")) {
//                  if (obj.has("id") && obj.getInt("id") > 0) {
//                    itemId = obj.getInt("id");
//                    toStoryDetail(context, itemId);
//                  } else {
//                    toMainPage(context);
//                  }
                } else if (value.contains("h5") || value.contains("H5")) {
//                  if (obj.has("id") && Tools.isNotEmpty(obj.getString("id"))) {
//                    String targetUrl = obj.getString("id");
//                    Intent it = new Intent(context, SliderActivity.class);
//                    it.putExtra("link", targetUrl);
//                    it.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
//                    context.startActivity(it);
//                  } else {
//                    toMainPage(context);
//                  }
                } else if (value.contains("discovery_sound")) {

                    if (!obj.isNull("mac_id")) {
                        String macIdd = obj.getString("mac_id");

                        Intent it = new Intent(context, MainActivity.class);
                      it.putExtra("pageindex", 1);
                      it.putExtra("maciiiid", macIdd);
                  it.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK|Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED|Intent.FLAG_ACTIVITY_CLEAR_TOP);
                  context.startActivity(it);



//                      Intent intent = new Intent("sound_msg_received");
//                      intent.putExtra("pageindex", 1);
//                      intent.putExtra("maciiiid", macIdd);
//                      context.sendBroadcast(intent);

                    }
//                  Intent it = new Intent(context, SpeakForYouActivity.class);
//                  it.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
//                  context.startActivity(it);

                }
              }
              Log.d(LogTag, "get custom value:" + value);
            }
          } else {
            Intent it = new Intent(context, LoginActivity.class);
            it.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            context.startActivity(it);
          }
        } catch (JSONException e) {
          Log.e(LogTag, e.toString());// received message is cannot be converted
                                      // json string.
          return;
        }
      }

    } else if (message.getActionType() == XGPushClickedResult.NOTIFACTION_DELETED_TYPE) {
      // 通知被清除啦。。。。
      // APP自己处理通知被清除后的相关动作
      text = "通知被清除 :" + message;
    }
    // Toast.makeText(context, "广播接收到通知被点击:" + message.toString(),
    // Toast.LENGTH_SHORT).show();

    // APP自主处理的过程。。。
    Log.d(LogTag, text);
    // show(context, text);
  }

  private void toStoryDetail(final Context context, final int storyId) {

    new AsyncTask<Void, Void, ResponseResult>() {
      @Override
      protected void onPostExecute(ResponseResult result) {
        if (Tools.isNotEmpty(result) && result.isSuccess()) {
          try {
            JSONObject jsonObject = new JSONObject(result.data);
            CarlaClassicVo ccv = new CarlaClassicVo();
            ccv.id = storyId; // );

            Intent recode = new Intent();
            if (!jsonObject.isNull("name")) {
              ccv.name = jsonObject.get("name").toString();
            }

            if (!jsonObject.isNull("lines")) {
              ccv.lines = jsonObject.get("lines").toString(); // );
            }

            if (!jsonObject.isNull("reslen")) {
              ccv.length = Integer
                  .parseInt(jsonObject.get("reslen").toString()); // /);
            }

            if (!jsonObject.isNull("url")) {
              ccv.url = jsonObject.get("url").toString();// );
            }

            if (!jsonObject.isNull("cover")) {
              ccv.cover = jsonObject.get("cover").toString(); // );
            }

            Bundle bundle = new Bundle();
            bundle.putSerializable("carlaclassic", ccv);
            recode.putExtras(bundle);
            recode.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        //    recode.setClass(context, RecordActivity.class);

            context.startActivity(recode);
          } catch (JSONException e) {

            e.printStackTrace();
          }
        }
      }

      @Override
      protected ResponseResult doInBackground(Void... params) {

        LeUser lu = MyTeacherApp.getInstance().getUserTeacher();
        HashMap<String, Object> param_ = new HashMap<String, Object>();
        param_.put(HttpUtils.TAG_SNO_I, lu.sno);
        param_.put(HttpUtils.TAG_KEY_I, HttpUtils.KEY);

        return HttpUtils.startRequest(HttpUtils.API_URL + "/api/story/"
            + storyId, param_, HttpUtils.TAG_GET_REQUEST);

      }

    }.execute();

  }

  private void toMainPage(Context ctx) {
    Intent it = new Intent(ctx, MainActivity.class);
    it.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
    ctx.startActivity(it);
  }

  @Override
  public void onRegisterResult(Context context, int errorCode,
      XGPushRegisterResult message) {

    if (context == null || message == null) {
      return;
    }
    String text = "";
    if (errorCode == XGPushBaseReceiver.SUCCESS) {
      text = message + "注册成功";
      // 在这里拿token
      String token = message.getToken();
    } else {
      text = message + "注册失败，错误码：" + errorCode;
    }
    Log.d(LogTag, text);
    // show(context, text);
  }

  // 消息透传
  @Override
  public void onTextMessage(Context context, XGPushTextMessage message) {

    String text = "收到消息:" + message.toString();
    // 获取自定义key-value
    String customContent = message.getCustomContent();
    if (customContent != null && customContent.length() != 0) {
      try {
        JSONObject obj = new JSONObject(customContent);
        // key1为前台配置的key
        if (!obj.isNull("d")) {
          String value = obj.getString("d");
          // if (Tools.isNotEmpty(value)) {
          // if (value.contains("chat")) {
          // context.startActivity(new Intent(context,
          // TalkToBabyActivity.class));
          // }
          // }
          Log.d(LogTag, "get custom value:" + value);
        }
        // ...
      } catch (JSONException e) {
        e.printStackTrace();
      }
    }
    // APP自主处理消息的过程...
    Log.d(LogTag, text);
    // show(context, text);
  }

}
